<?php


namespace PKApp\Member;


use PKApp\Member\Classes\UserCtrl;
use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\MatchHelper;

class ApiRegister extends UserCtrl
{

    public function Main()
    {
        $params = $this->model();
        $entity = $this->serviceByUser()->GetEntity(['userName' => $params['userName']]);
        !Arrays::Is($entity) ?: $this->noticeByJson('Exists_userName');
        $entity = $this->serviceByUser()->GetEntity(['email' => $params['email']]);
        !Arrays::Is($entity) ?: $this->noticeByJson('Exists_email');
        $this->serviceByUser()->Add($params);
        $this->json();
    }

    protected function model(): array
    {
        $params = ['userName' => $this->checkPostFieldIsEmpty('userName', 'Empty_userName'),
            'email' => $this->checkPostFieldIsEmpty('email', 'Empty_userEmail'),];
        $pwd = $this->checkPostFieldIsEmpty('password', 'Empty_userPwd');
        $confirmPwd = $this->checkPostFieldIsEmpty('confirmPwd', 'Empty_confirmPwd');
        MatchHelper::MatchFormat('letter_num', $params['userName'], 'Err_userName');
        MatchHelper::MatchFormat('email', $params['email'], 'Err_email');
        MatchHelper::MatchFormat('password', $pwd, 'Err_pwd');
        if (strlen($pwd) < 6) {
            $this->noticeByJson('Empty_userPwd');
        } elseif ($pwd != $confirmPwd) {
            $this->noticeByJson('Err_confirmPwd');
        }
        return array_merge($params,
            $this->serviceByUser()->createNewPassWord($pwd),
            ['createTime' => TIMESTAMP, 'modelId' => 2, 'groupId' => 5]);
    }
}